package top.revery.task.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;
import top.revery.api.api.user.IMyCollectionApi;
import top.revery.api.config.UserPageData;
import top.revery.api.entity.user.BaseMyCollection;

import top.revery.api.entity.user.BaseUserKol;
import top.revery.api.entity.vo.BaseColllectionVo;
import top.revery.task.dto.KolDto;
import top.revery.task.dto.MyCollectionDto;
import top.revery.task.service.MyCollectionService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author denghao
 * @title
 * @package 我的收藏
 * @date 2019/12/17 11:42
 */
@RestController
@Transactional
public class MyCollectionController implements IMyCollectionApi {
    @Autowired
    private MyCollectionDto myCollectionDto;
    @Autowired
    private MyCollectionService myCollectionService;
    @Autowired
    private KolDto kolDto;

    @Override
    public BaseMyCollection save(BaseMyCollection baseMyCollection) {
        try {
            return myCollectionDto.save(baseMyCollection);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public BaseMyCollection findById(Long id) {

        try {
            Optional<BaseMyCollection> byId = myCollectionDto.findById(id);
            if (byId.isPresent()) {
                return byId.get();
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public UserPageData getList(int pageNum, int pageSize, Map map) {
        Page<BaseMyCollection> pageList = myCollectionService.findPage(pageNum, pageSize, map);
        List<BaseMyCollection> list = pageList.getContent();
        List<BaseColllectionVo> list1 = new ArrayList<>();
        for (BaseMyCollection baseMyCollection :list){
              BaseColllectionVo baseColllectionVo =new BaseColllectionVo();
              BaseUserKol baseUserKol=kolDto.findById(baseMyCollection.getUserId()).get();
              baseColllectionVo.setBaseMyCollection(baseMyCollection);
              baseColllectionVo.setBaseUserKol(baseUserKol);
              list1.add(baseColllectionVo);
        }
        UserPageData userPageData = new UserPageData();
        userPageData.list = list1;
        userPageData.rows = pageList.getTotalElements();
        return userPageData;
    }
}
